import { Browser } from "puppeteer-core"
import lodash from "lodash"
import prettier from "prettier"

import { useNode } from "@/hooks"

// import { type ITask } from "@/interface"

import dutyConfigJson from "../../env.duty.json"

const { fs, path, os, child_process, util } = useNode()

const { promisify } = util

const { spawnSync, exec, execSync } = child_process

const getLastPage = (browser: Browser) =>
  browser.pages().then(pages => pages.pop())

const setPowershellUtf8 = () => {
  // 使用 PowerShell 命令设置控制台编码为 UTF-8
  const powershellCmd = "powershell"

  const powershellArgs = [
    "-Command",
    "$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
  ]

  // 执行 PowerShell 命令
  spawnSync(powershellCmd, powershellArgs)
}

const getAllnetshInterface = () => {
  const ls = spawnSync("netsh", ["interface", "show", "interface"], {
    encoding: "utf-8",
  })

  const interfaces = ls.stdout
    .toString()
    .split("\r\n")
    .filter(Boolean)
    .slice(-2)
    .map(i => i.split(" ").filter(Boolean))
    .map(i =>
      Object.fromEntries(lodash.zip(["admin", "state", "type", "name"], i)),
    )

  return interfaces
}

const setNetInterface = async (ip: string) => {
  if (os.platform() === "darwin") {
    console.error("Mac system does not support")
    return null
  }

  setPowershellUtf8()

  const execPromise = promisify(exec)

  const interfaces = getAllnetshInterface().filter(i => i.state)

  for (const item of interfaces) {
    const admin = ip == item.name ? "enable" : "disable"

    await execPromise(
      `netsh interface set interface ${item.name} admin=${admin}`,
    )
  }
}

const killChrome = () => {
  const command = `taskkill /F /IM chrome.exe`
  const execPromise = promisify(exec)
  return execPromise(command)
}

const getCurrentNetInterface = () => {
  if (os.platform() === "darwin") {
    console.error("Mac system does not support")
    return null
  }

  setPowershellUtf8()

  const interfaces = getAllnetshInterface()

  const { name } = interfaces.find(i => i.state == "Connected")

  return name
}

class TaskCenter {
  static createProxy<T = Record<string, unknown>>(jsonPath: string) {
    const json = JSON.parse(fs.readFileSync(jsonPath, "utf8"))

    const baseData = Object.assign({}, json)

    const debounce = lodash.debounce(async (src: string, data: object) => {
      const jsonStr = JSON.stringify(data)

      const formattedJson = await prettier.format(jsonStr, {
        parser: "json",
      })

      fs.writeFileSync(src, formattedJson)
    }, 300)

    return <T>new Proxy(baseData, {
      set(target, propKey, value, receiver) {
        const setResult = Reflect.set(target, propKey, value, receiver)

        if (setResult) {
          debounce(jsonPath, target)
        }

        return setResult
      },
    })
  }
}

const dp = path.join(os.homedir(), "Desktop")

const transform2WinPath = (p: string) => path.join(p.replace(/^.+Desktop/, dp))

const fullScreenChrome = () => {
  const activeAhkScriptPath = path.resolve(__dirname, "../scripts/active.ahk")

  try {
    // 同步执行命令
    execSync(activeAhkScriptPath)
  } catch (error) {
    console.error(`执行chrome全屏出错: ${error}`)
  }
}

const getMasterIp = () => {
  const [{ ip }] = dutyConfigJson.ipMap.filter(i => i.isMaster)
  return ip
}

const resetMasterIp = () => {
  const masterIp = getMasterIp()
  return setNetInterface(masterIp)
}

export {
  resetMasterIp,
  getLastPage,
  getCurrentNetInterface,
  TaskCenter,
  setNetInterface,
  killChrome,
  transform2WinPath,
  dp as desktopPath,
  fullScreenChrome,
  getMasterIp,
  setNetInterface as setIp,
}
